<!--
 * @Author: wangshuguang
 * @Date: 2022-02-18 15:07:02
 * @LastEditTime: 2022-10-27 14:17:13
 * @LastEditors: wangshuguang
 * @Description: 开户页面
-->
<template>
  <div class="openAccount">
    <HeaderComp title="开通享惠生活" >
      <div slot="rightContent" class="guideBtn" @click="guideVis = true">指引</div>
    </HeaderComp>
    <div class="title">主营行业</div>
    <input type="text"  class="selectMoney" v-model="form.bizPkgText" readonly @click="mainBusVis = true" placeholder="请选择主营行业">
    <div class="title leftLine">商户套餐</div>

    <template v-for="(pkg,idx) of pkgObj" >
      <div :key="'pkg_'+idx" v-if="pkg.list.length">
        <div class="dateTxt">{{ pkg.name }}</div>
        <meal-list :mealDataList='pkg.list' :active="activePkgId" @change="changeMeal"/>
      </div>
    </template>

    <!-- 流量三期版本⬆⬆⬆⬆ -->
    <!-- <div class="labelText">{{mealLabelText}}</div> -->

    <!-- 支付方式 -->
    <div class="title">支付方式</div>
    <div>
      <van-radio-group v-model="form.payType">
        <div class="payType">
          <van-radio name="WALL"
            checked-color="#FFB72F"
            icon-size="24px"
            :disabled="canWallPay" />
          <div class="payTypeContent">
            钱包余额（剩余￥{{accountBal}}）
            <div class="balanceLabel"
              v-if="form.payAmount && accountBal < form.payAmount">余额不足，请先充值</div>
          </div>
          <!-- <div class="btn" @click="showRecharge">去充值</div> -->
        </div>
        <div class="payType mg-t-20">
          <van-radio name="ZFB"
            checked-color="#FFB72F"
            icon-size="24px" />
          <div class="payTypeContent">
            支付宝支付
          </div>
        </div>
      </van-radio-group>
    </div>
    <!-- 按钮组 -->
    <div class="btnList">
      <div class="rule">
        <van-radio-group v-model="form.agree"
          class="mg-r-20">
          <van-radio name="1"
            checked-color="#FFB72F"
            icon-size="24px" />
        </van-radio-group>
        同意<span class="aBlank"
          @click="agreementVisible = true">会员营销系统服务协议</span>
      </div>
      <van-button type="primary"
        class="submitBtn"
        @click="submit">提交</van-button>
    </div>
    <!-- 充值弹框 -->
    <van-dialog v-model="rechargeVisible"
      round
      position="bottom"
      show-cancel-button
      confirmButtonText="保存至相册"
      className="rechargeDialog"
      :before-close="qrCodeClose">
      <div class="rechargeTitle">充值钱包余额</div>
      <!-- <img src="../../assets/img/flow/qrcode.png" alt=""> -->
      <div ref="qrCode"
        class="qrCode"
        v-if="rechargeVisible"></div> 
      <div class="qrcodeLabel">说明：请截屏或保存二维码至本地相册， 并使用微信/支付宝扫一扫进行扫码支付</div>
    </van-dialog>
    <!-- 选择主营行业 -->
    <van-popup v-model="mainBusVis" round position="bottom">
      <van-picker
        title="选择主营行业"
        show-toolbar
        :columns="columns"
        @cancel="mainBusVis = false"
        @confirm="mainBusConFirm"
      />
    </van-popup>
    <!-- 支付框 -->
    <van-dialog className="openAccountPwdDialog"
      v-model="pwdVisible"
      show-cancel-button
      :before-close="pwdClose">
      <div class="info">
        <div class="closeIcon"></div>
        <div class="title">请输入支付密码</div>
        <div class="payAmount">￥{{form.payAmount}}</div>
        <div class="payTypeLabel">
          <span>支付方式</span>
          <span>钱包余额</span>
        </div>
      </div>
      <van-password-input :value="form.pwd"
        :focused="showKeyboard"
        @focus="showKeyboard = true" />
    </van-dialog>
    <!-- 协议内容 -->
    <van-popup v-model="agreementVisible"
      round
      position="bottom">
      <agreementPage />
    </van-popup>
    <!-- 数字键盘 -->
    <van-number-keyboard z-index="3000"
      v-model="form.pwd"
      :show="showKeyboard"
      @blur="showKeyboard = false" />
    <!-- 指引弹框 -->
    <openAcountGuide v-model="guideVis" :openAccountInfo='openAccountInfo'/>
  </div>
</template>

<script>
import { Dialog } from "vant";
import { savePicture, payFormSubmit } from "@/utils/utils";
import agreementPage from "./components/agreementPage.vue";
import mealList from "./components/mealList.vue";
import openAcountGuide from "./components/openAcountGuide.vue";
import {
  getMercOpenPkg,
  calculateManyShop,
  queryEnjoyAccountBalance,
  openEnjoyFavour,
  createPayAmountQrCode,
  wapAliPay,
} from "@/api/flow/index";
import { payOpenAmount, queryIndustryList, queryOpenEnjoyAllInfo } from "@/api/flow/openAcount";

import { mapGetters } from "vuex";
import QRCode from "@keeex/qrcodejs-kx";
export default {
  components: { agreementPage, mealList, openAcountGuide },
  data() {
    return {
      accountBal: 0,
      mainBusVis: false,
      pwdVisible: false,
      rechargeVisible: false,
      agreementVisible: false,
      showKeyboard: false,
      guideVis: true,
      mealLabelText: "",
      calcMealData: {},
      openAccountInfo: {},
      columns:[],
      form: {
        agree: "",
        pwd: "",
        payAmount: 0,
        payType: "WALL",
      },
      qrCodeObj: null,
      submitInfo: {},
      // 套餐类型 0：月套餐；1：年套餐；2：交互套餐；3：季套餐；4：半年套餐
      pkgObj:{
        'pkg_0': { list: [], name: '月套餐' },
        'pkg_3': { list: [], name: '季套餐' },
        'pkg_4': { list: [], name: '半年套餐' },
        'pkg_1': { list: [], name: '年套餐' },
      },
      activePkgId: "",
      nowMeal: {},
      status: 1,
    };
  },
  computed: {
    canWallPay() {
      return this.accountBal < this.form.payAmount;
    },
    ...mapGetters(["flowQueryData"]),
  },
  mounted() {
    this.getBaseData();
  },
  methods: {
    mainBusConFirm(item){
      this.form.bizPkgText = item.text
      this.form.bizPkgId = item.value
      this.mainBusVis = false
    },
    // 计算多租户加租实际金额
    calcBalance() {
      if (!this.form.payAmount || !this.nowMeal.price) {
        return;
      }
      const { merchantId } = this.flowQueryData;
      calculateManyShop({
        merchantId: merchantId,
        payFlowBalance: this.form.payAmount,
        pkgFlowCost: this.nowMeal.price,
        addPercent: this.nowMeal.addRentRatio,
        restrictFlag: this.nowMeal.restrictFlag,
      }).then((res) => {
        console.log("calculateManyShop", res);
        const { code, data, msg } = res.data;
        if (!data) {
          this.$toast(msg);
        } else {
          this.calcMealData = data;
          if (data) {
            this.mealLabelText = `订购${this.nowMeal.tempName}后，预计账户剩余${data.surplusFlow}流量余额`;
          }
        }
      });
    },
    getBaseData() {
      const { deptId, merchantNo, merchantId } = this.flowQueryData;
      // 获取账户余额
      queryEnjoyAccountBalance({
        deptId,
        merchantId,
        userType: "merch",
      }).then((res) => {
        this.accountBal = res.data.data || 0;
      });
      // 获取套餐列表
      getMercOpenPkg({ deptId, merchantNo }).then((res) => {
        console.log("获取套餐列表", res);
        // this.nowMeal = this.mealList[0]
        // 去除交互次数套餐
        let temporary = res.data.data.filter((item) => item.type != 2);
        for (let i = 0; i < temporary.length; i++) {
          let obj = temporary[i]
          this.pkgObj['pkg_'+obj.type]['list'].push(obj)
        }
      });
      // 获取主营行业列表
      queryIndustryList().then(res => {
        console.log('获取主营行业列表res',res)
        this.columns = res.data.data.map(item => {
          return {
            ...item,
            text: item.name,
            value: item.id
          }
        })
      })
      queryOpenEnjoyAllInfo({deptId}).then(res => {
        this.openAccountInfo = res.data.data
      })
    },
    qrCodeClose(type, done) {
      if (type == "confirm") {
        const { _oDrawing } = this.qrCodeObj;
        savePicture(_oDrawing._elImage.currentSrc);
        this.$toast("保存成功");
        done(false);
      } else {
        done();
      }
    },
    showRecharge() {
      const { merchantId, deptId, agentId } = this.flowQueryData;
      const { payType, payAmount } = this.form;

      if (!payAmount) {
        this.$toast("请选择开通金额！");
        return;
      }

      let obj = {
        agentId,
        deptId,
        payAmount: payAmount,
        payType: payType,
        userId: merchantId,
        userType: "merch",
      };
      createPayAmountQrCode(obj).then((res) => {
        console.log("res", res);
        if (res.data.code == 0) {
          this.rechargeVisible = true;
          this.$nextTick(() => {
            this.qrCodeObj = new QRCode(this.$refs.qrCode, {
              text: res.data.data, // 需要转换为二维码的内容
              width: 354,
              height: 354,
              colorDark: "#000000",
              colorLight: "#ffffff",
            });
            console.log("qrCodeObj", this.qrCodeObj);
          });
        }
      });
    },
    submit() {
      console.log("看看数据", this.nowMeal);
      const { merchantNo, merchantId, deptId, agentId, merchantFullName } = this.flowQueryData;
      if(!this.form.bizPkgId){
        this.$toast("请选择主营行业！");
        return;
      }else if (!this.nowMeal.price) {
        this.$toast("请选择商户套餐！");
        return;
      } else if (!this.form.payType) {
        this.$toast("请选择支付方式！");
        return;
      }else if (!this.form.agree) {
        this.$toast("请先同意服务条款！");
        return;
      }
      if (this.form.payType == "WALL") {
        if (this.nowMeal.price > this.accountBal) {
          this.$toast("钱包余额不足，请切换支付方式！");
          return;
        }
        this.pwdVisible = true;
      } else {
        this.zfbPay();
      }
    },
    zfbPay() {
      const {
        merchantId,
        deptId,
        agentId,
        merchantNo,
        shopId,
        merchantFullName,
      } = this.flowQueryData;
      const { payType, payAmount, bizPkgId } = this.form;
      // 提交开户
      let obj = {
        agentId: agentId,
        bizPkgId,
        comboTotalCost: this.calcMealData.comboTotalCost,
        deptId: deptId,
        merchantFullName: merchantFullName,
        merchantId: merchantId,
        merchantNo: merchantNo,
        merchantPkgId: this.nowMeal.id,
        orgId: this.nowMeal.orgId,
        packageFlowBalance: this.nowMeal.monthFlow,
        payAmount: payAmount,
        payFlowBalance: payAmount,
        payType: payType,
        pkgFlowCost: this.nowMeal.price,
        pkgTempName: this.nowMeal.tempName,
        restrictFlag: this.nowMeal.restrictFlag,
        shopId: shopId,
        surplusFlow: this.calcMealData.surplusFlow,
      };
      console.log("pwdClose", obj);
      // 先开户 再修改余额
      openEnjoyFavour(obj).then((res) => {
        if (res.data.data) {
          let submitInfo = res.data.data;

          // 支付宝支付
          let obj = {
            agentId,
            bizPkgId,
            openFlag: 1,
            routing: "openAccountResult",
            quitRouting: `openAccountResult?payType=ZFBERR`,
            autoBusinessNo: submitInfo.autoBusinessNo,
            businessNo: submitInfo.businessNo,
            comboBaseCost: this.nowMeal.price,
            comboTotalCost: this.calcMealData.comboTotalCost,
            dedBusinessNo: submitInfo.dedBusinessNo,
            deptId,
            manyShopCost: this.calcMealData.manyShopCost,
            merchantFullName,
            merchantId,
            merchantNo,
            orgId: this.nowMeal.orgId,
            payFlowBalance: this.form.payAmount,
            payType: this.form.payType,
            pkgId: this.nowMeal.id,
            shopCount: this.calcMealData.shopCount,
            subject: "充值流量余额",
            surplusFlow: this.calcMealData.surplusFlow,
            totalAmount: this.form.payAmount,
          };
          wapAliPay(obj).then((res) => {
            console.log("res", res);
            payFormSubmit(res.data.data);
          });
        } else {
          this.$toast(res.data.msg);
          done(false);
        }
      });
    },
    pwdClose(type, done) {
      console.log("pwdClose", done, type);
      if (type == "confirm") {
        // this.$router.push('payResult')
        // done()

        const {
          merchantId,
          deptId,
          agentId,
          merchantNo,
          shopId,
          merchantFullName,
        } = this.flowQueryData;
        const { payType, payAmount, bizPkgId } = this.form;
        // 提交开户
        let obj = {
          agentId: agentId,
          bizPkgId,
          comboTotalCost: this.calcMealData.comboTotalCost,
          deptId: deptId,
          merchantFullName: merchantFullName,
          merchantId: merchantId,
          merchantNo: merchantNo,
          merchantPkgId: this.nowMeal.id,
          orgId: this.nowMeal.orgId,
          packageFlowBalance: this.nowMeal.monthFlow,
          payAmount: payAmount,
          payFlowBalance: payAmount,
          payType: payType,
          pkgFlowCost: this.nowMeal.price,
          pkgTempName: this.nowMeal.tempName,
          restrictFlag: this.nowMeal.restrictFlag,
          shopId: shopId,
          surplusFlow: this.calcMealData.surplusFlow,
        };
        console.log("pwdClose", obj);
        // 先开户 再修改余额
        openEnjoyFavour(obj).then((res) => {
          if (res.data.data) {
            let submitInfo = res.data.data;
            let payObj = {
              bizPkgId,
              dedBusinessNo: submitInfo.dedBusinessNo,
              deptId: submitInfo.deptId,
              merchantId: submitInfo.merchantId,
              businessNo: submitInfo.businessNo,
              autoBusinessNo: submitInfo.autoBusinessNo,
              orgId: this.nowMeal.orgId,
              pkgId: this.nowMeal.id,
              changeAmount: this.nowMeal.price,
              comboTotalCost: this.calcMealData.comboTotalCost,
              comboBaseCost: this.nowMeal.price,
              surplusFlow: this.calcMealData.surplusFlow,
              manyShopCost: this.calcMealData.manyShopCost,
              shopCount: this.calcMealData.shopCount,
              payPassword: this.form.pwd,
            };
            payOpenAmount(payObj).then((payRes) => {
              console.log("res", res);
              if (payRes.data.code == 0) {
                this.$router.push({
                  path: "/openAccountResult",
                  query: payRes.data.data,
                });
              } else {
                this.$toast(payRes.data.msg);
                done(false);
              }
            });
          } else {
            this.$toast(res.data.msg);
            done(false);
          }
        });
      } else {
        this.form.pwd = "";
        done();
      }
    },
    showTip(num) {
      Dialog.alert({
        message: `多门店加租：每增加一家门店，流量套餐月租价格叠加${num}%`,
      });
    },
    changeMeal(item) {
      this.nowMeal = item;
      // 需求调整 取消开户金额，默认开户金额字段等于套餐金额
      this.form.payAmount = item.price
      if (JSON.stringify(this.nowMeal) != "{}") {
        this.activePkgId = item.id
      }

      this.calcBalance();
      // 如果超出钱包剩余金额  切换支付方式
      if (
        this.accountBal < this.form.payAmount &&
        this.form.payType == "WALL"
      ) {
        this.form.payType = "ZFB";
      }
    },
  },
};
</script>

<style lang='less'>
.guideBtn{
  color: #ffb72f;
}
.leftLine {
  border-left: 6px solid #ffb72f;
  padding-left: 13px;
}
.openAccountPwdDialog {
  top: 30%;
  .info {
    padding: 20px;
    .title {
      font-size: 32px;
      color: #131313;
      text-align: center;
    }
    .payAmount {
      font-size: 60px;
      color: #131313;
      text-align: center;
      margin-bottom: 67px;
    }
    .payTypeLabel {
      display: flex;
      justify-content: space-between;
      color: #131313;
      opacity: 0.7;
      margin-bottom: 60px;
    }
  }
}
.rechargeDialog {
  .van-dialog__footer {
    .van-dialog__cancel {
      color: #ffb72f;
    }
    .van-dialog__confirm {
      background: #ffb72f;
      color: #fff;
    }
  }
  .van-dialog__content {
    padding: 20px;
    text-align: center;
    .rechargeTitle {
      color: #131313;
      font-size: 34px;
    }
    .qrCode {
      margin: 60px 70px;
      img,
      canvas {
        width: 100%;
      }
    }
  }
}
.openAccount {
  height: 100%;
  padding: 40px 40px 250px;
  overflow: auto;
  font-size: 26px;
  .title {
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 26px;
  }
  .selectMoney {
    width: 100%;
    height: 79px;
    font-size: 28px;
    border: 1px solid #e7e7e7;
    background: #fff;
    border-radius: 15px;
    margin-bottom: 26px;
    padding-left: 20px;
    option {
      font-size: 10px;
    }
  }
  .labelText {
    opacity: 0.6;
    color: #131313;
    font-size: 26px;
    margin-bottom: 88px;
    > div {
      margin-bottom: 26px;
    }
    .flowRule {
      color: #ffb72f;
    }
  }
  .payType {
    display: flex;
    .payTypeContent {
      font-size: 32px;
      margin-left: 20px;
      flex: 1;
      .balanceLabel {
        color: #f05357;
        font-size: 28px;
      }
    }
    .btn {
      font-size: 28px;
      color: #fff;
      background: #ffb72f;
      border-radius: 27px;
      width: 130px;
      line-height: 54px;
      height: 54px;
      text-align: center;
    }
  }
  /* 老版本⬆ */

  .btnList {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    .rule {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26px;
      .aBlank {
        color: #ffb72f;
      }
    }
    .submitBtn {
      background: #ffb72f;
      border-color: #ffb72f;
      height: 98px;
      width: 100%;
      font-size: 32px;
      margin-top: 40px;
    }
  }
  .dateTxt {
    font-size: 28px;
    font-family: PingFang SC;
    font-weight: 500;
    color: #131313;
    margin: 49px 0 30px;
  }
}
</style>